<script setup>
import {ref, onBeforeUnmount, reactive, onUnmounted, onMounted} from 'vue'
import {useSerialStore} from "../../stores/serialStore.js";
import TerminalComponent from '../../components/TerminalComponent.vue';
import {ElMessage} from "element-plus";

const activeTab = ref('first')
// 组件引用
const { serialState, updateConfig, connect, disconnect } = useSerialStore()
const terminalRef = ref(null)
// 响应式状态
const connecting = ref(false)
const serialConfig = reactive(serialState.config) //串口配置 改为响应式引用store配置
// 串口配置选项
const baudRateOptions = [9600, 19200, 38400, 57600, 115200]
const bufferSizeOptions = [255, 512, 1024]
const dataBitsOptions = [7, 8]
const stopBitsOptions = [1, 2]
const parityOptions = [{ label: '无', value: 'none' }, { label: '奇校验', value: 'odd' }, { label: '偶校验', value: 'even' }]

// 组件挂载时绑定回调
onMounted(() => {
  serialState.instance.onDataReceived = handleSerialData
  serialState.instance.onDisconnect = handleDisconnect
})

// 组件卸载时解除回调
onUnmounted(() => {
  serialState.instance.onDataReceived = null
  serialState.instance.onDisconnect = null
})




///

// 连接/断开处理
const toggleConnection = async () => {
  try {
    connecting.value = true
    if (serialState.isConnected) {    //断开连接(使用全局状态)
      await disconnect()  // 直接调用store方法
      // await new Promise(resolve => setTimeout(resolve, 200));// 延迟置空保证清理完成
      // isConnected.value = false
      // serialPort.port = null // 确保Vue组件中的引用置空
      ElMessage.success('已断开连接')
    } else {    //准备连接
      // if (serialPort.port) await serialPort.disconnect()
      // const success = await serialPort.connect(serialConfig);
      const success = await connect() // 使用store方法
      if (success) {// 重新绑定事件
        // serialPort.onDataReceived = handleSerialData
        // serialPort.onDisconnect = handleDisconnect
        // isConnected.value = true
        ElMessage.success('串口连接成功')
      }
    }
  } catch (error) {
    ElMessage.error(`连接失败: ${error.message}`)
  } finally {
    connecting.value = false
  }
}
const handleDisconnect = () => {// 断开处理
  // isConnected.value = false
  terminalRef.value.write('\r\n[连接已断开]\r\n')
  ElMessage.warning('连接已断开')
}
const handleTerminalData = (data) => {// 终端数据处理
  // if (isConnected.value) serialPort.write(data)
  if (serialState.isConnected) serialState.instance.write(data) // 使用全局实例
}
const handleSerialData = (data) => {
  terminalRef.value.write(data)
}
</script>


<template>
<div class="main-container">
  <el-tabs v-model="activeTab"><!--@tab-click="handleClick"-->
    <el-tab-pane label="配置" name="first">
      <div class="config-pane">
        <el-form :model="serialConfig" class="config-form">
          <el-form-item label="状态：">
            <el-button
                style="flex: 1"
                @click="toggleConnection"
                :type="serialState.isConnected?'success':'primary'"
                :loading="connecting">
              {{ serialState.isConnected ? '关闭串口' : '打开串口' }}
            </el-button>
          </el-form-item>
          <el-form-item label="缓冲区" prop="bufferSize">
            <el-select v-model="serialConfig.bufferSize">
              <el-option v-for="rate in bufferSizeOptions" :key="rate" :value="rate" :label="`${rate} bit`"/>
            </el-select>
          </el-form-item>
          <el-form-item label="波特率" prop="baudRate">
            <el-select v-model="serialConfig.baudRate">
              <el-option v-for="rate in baudRateOptions" :key="rate" :value="rate" :label="`${rate} baud`"/>
            </el-select>
          </el-form-item>
          <el-form-item label="数据位" prop="dataBits">
            <el-select v-model.number="serialConfig.dataBits">
              <el-option v-for="bits in dataBitsOptions" :key="bits" :value="bits" :label="`${bits} 位`"/>
            </el-select>
          </el-form-item>
          <el-form-item label="校验位" prop="parity">
            <el-select v-model="serialConfig.parity">
              <el-option v-for="item in parityOptions" :key="item.value" :value="item.value" :label="item.label"/>
            </el-select>
          </el-form-item>
          <el-form-item label="停止位" prop="stopBits">
            <el-select v-model.number="serialConfig.stopBits">
              <el-option v-for="bits in stopBitsOptions" :key="bits" :value="bits" :label="`${bits} 位`"/>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </el-tab-pane>
    <el-tab-pane label="指令" name="second">Config</el-tab-pane>
    <el-tab-pane label="Role" name="third">Role</el-tab-pane>
    <el-tab-pane label="Task" name="fourth">Task</el-tab-pane>
  </el-tabs>
  <!-- 终端交互界面 -->
  <TerminalComponent
      ref="terminalRef"
      @data="handleTerminalData"
      class="terminal-container"
  />
</div>
</template>

<style scoped>
.main-container {
  display: flex;
  height: 100%;
  .el-tabs{
    width: 25%;
  }
}
.config-pane {
  display: flex;
  flex-direction: column;
  height: 100vh;
  padding: 0px;
}



.terminal-container {
  flex: 1;
  margin-left: 10px;
  min-height: 200px;
  border: 1px solid #ebeef5;
}


</style>